package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.textfield.TextInputEditText;

import java.util.ArrayList;
import java.util.List;

public class EventListActivity extends AppCompatActivity {
    private TextInputEditText etEventId;
    private TextInputEditText etEventName;
    private Button btnAdd;
    private Button btnDelete;
    private Button btnUpdate;
    private Button btnQuery;
    private RecyclerView rvEvents;
    private EventAdapter eventAdapter;
    private String currentUserEmail;
    private GameEventDBHelper dbHelper;
    // 1. 新增：声明返回按钮
    private TextView tvBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_list);

        // 接收用户邮箱（数据隔离标识）
        currentUserEmail = getIntent().getStringExtra("USER_EMAIL");
        if (currentUserEmail == null || currentUserEmail.isEmpty()) {
            currentUserEmail = "default@example.com";
        }

        // 初始化数据库帮助类
        dbHelper = new GameEventDBHelper(this);

        // 初始化控件（包含新增的返回按钮）
        initViews();
        initRecyclerView();
        setupButtonListeners();
        // 新增：设置返回按钮点击逻辑
        setupBackListener();
        loadEventsFromDB();
    }

    private void initViews() {
        etEventId = findViewById(R.id.et_event_id);
        etEventName = findViewById(R.id.et_event_name);
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQuery = findViewById(R.id.btn_query);
        rvEvents = findViewById(R.id.rv_events);
        // 2. 新增：初始化返回按钮（对应布局中id为tv_back的控件）
        tvBack = findViewById(R.id.tv_back);
    }

    private void initRecyclerView() {
        rvEvents.setLayoutManager(new LinearLayoutManager(this));
        eventAdapter = new EventAdapter();
        rvEvents.setAdapter(eventAdapter);
    }

    private void setupButtonListeners() {
        btnAdd.setOnClickListener(v -> addEvent());
        btnDelete.setOnClickListener(v -> deleteEvent());
        btnUpdate.setOnClickListener(v -> updateEvent());
        btnQuery.setOnClickListener(v -> queryEvent());
    }

    // 3. 新增：返回按钮点击逻辑（跳回HomeActivity）
    private void setupBackListener() {
        tvBack.setOnClickListener(v -> {
            // 方式1：如果当前页是从HomeActivity跳转来的，直接关闭当前页即可返回
            finish();


        });
    }

    // 从数据库加载当前用户的所有活动（原有逻辑不变）
    private void loadEventsFromDB() {
        List<GameEvent> events = dbHelper.getEventsByUser(currentUserEmail);
        eventAdapter.setData(events);
    }

    // 新增活动（原有逻辑不变）
    private void addEvent() {
        String id = etEventId.getText().toString().trim();
        String name = etEventName.getText().toString().trim();
        if (!id.isEmpty() && !name.isEmpty()) {
            GameEvent event = new GameEvent(
                    id, name, "默认IP", "2025-01-01", "默认地点", "默认描述", "参与人数: 0人", currentUserEmail
            );
            dbHelper.addEvent(event);
            loadEventsFromDB();
            clearInputs();
        }
    }

    // 删除活动（原有逻辑不变）
    private void deleteEvent() {
        String id = etEventId.getText().toString().trim();
        if (!id.isEmpty()) {
            dbHelper.deleteEvent(id, currentUserEmail);
            loadEventsFromDB();
            clearInputs();
        }
    }

    // 修改活动（原有逻辑不变）
    private void updateEvent() {
        String id = etEventId.getText().toString().trim();
        String name = etEventName.getText().toString().trim();
        if (!id.isEmpty() && !name.isEmpty()) {
            GameEvent event = new GameEvent(
                    id, name, "默认IP", "2025-01-01", "默认地点", "默认描述", "参与人数: 0人", currentUserEmail
            );
            dbHelper.updateEvent(event);
            loadEventsFromDB();
            clearInputs();
        }
    }

    // 查询活动（原有逻辑不变）
    private void queryEvent() {
        String id = etEventId.getText().toString().trim();
        String name = etEventName.getText().toString().trim();
        List<GameEvent> events = dbHelper.queryEvents(currentUserEmail, id, name);
        eventAdapter.setData(events);
    }

    private void clearInputs() {
        etEventId.setText("");
        etEventName.setText("");
    }

    // RecyclerView适配器（原有逻辑不变）
    class EventAdapter extends RecyclerView.Adapter<EventViewHolder> {
        private List<GameEvent> data = new ArrayList<>();

        public void setData(List<GameEvent> newData) {
            this.data = newData;
            notifyDataSetChanged();
        }

        @Override
        public EventViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = EventListActivity.this.getLayoutInflater().inflate(R.layout.item_event, parent, false);
            return new EventViewHolder(view);
        }

        @Override
        public void onBindViewHolder(EventViewHolder holder, int position) {
            GameEvent event = data.get(position);
            holder.tvItemEventId.setText("活动编号: " + event.getEventId());
            holder.tvItemEventName.setText(event.getEventName());
            holder.tvItemEventTimeLocation.setText(event.getDate() + " | " + event.getLocation());
            holder.tvItemEventParticipants.setText(event.getParticipants());
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    // RecyclerViewViewHolder（原有逻辑不变）
    class EventViewHolder extends RecyclerView.ViewHolder {
        TextView tvItemEventId;
        TextView tvItemEventName;
        TextView tvItemEventTimeLocation;
        TextView tvItemEventParticipants;

        public EventViewHolder(View itemView) {
            super(itemView);
            tvItemEventId = itemView.findViewById(R.id.tv_item_event_id);
            tvItemEventName = itemView.findViewById(R.id.tv_item_event_name);
            tvItemEventTimeLocation = itemView.findViewById(R.id.tv_item_event_time_location);
            tvItemEventParticipants = itemView.findViewById(R.id.tv_item_event_participants);
        }
    }
}